package com.example.memo2.notification

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import com.example.memo2.data.model.Memo
import java.util.Date

class ReminderManager(private val context: Context) {
    
    private val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    
    fun setReminder(memo: Memo) {
        memo.reminderTime?.let { reminderTime ->
            // 只有当提醒时间在未来时才设置
            if (reminderTime.time > System.currentTimeMillis()) {
                val intent = Intent(context, ReminderReceiver::class.java).apply {
                    putExtra(ReminderReceiver.EXTRA_MEMO_ID, memo.id)
                    putExtra(ReminderReceiver.EXTRA_MEMO_TITLE, memo.title)
                    putExtra(ReminderReceiver.EXTRA_MEMO_CONTENT, memo.content)
                }
                
                val pendingIntent = PendingIntent.getBroadcast(
                    context,
                    memo.id.toInt(),
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
                )
                
                try {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        alarmManager.setExactAndAllowWhileIdle(
                            AlarmManager.RTC_WAKEUP,
                            reminderTime.time,
                            pendingIntent
                        )
                    } else {
                        alarmManager.setExact(
                            AlarmManager.RTC_WAKEUP,
                            reminderTime.time,
                            pendingIntent
                        )
                    }
                } catch (e: SecurityException) {
                    // 如果没有SCHEDULE_EXACT_ALARM权限，使用普通闹钟
                    alarmManager.set(
                        AlarmManager.RTC_WAKEUP,
                        reminderTime.time,
                        pendingIntent
                    )
                }
            }
        }
    }
    
    fun cancelReminder(memoId: Long) {
        val intent = Intent(context, ReminderReceiver::class.java)
        val pendingIntent = PendingIntent.getBroadcast(
            context,
            memoId.toInt(),
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        
        alarmManager.cancel(pendingIntent)
        pendingIntent.cancel()
    }
    
    fun updateReminder(memo: Memo) {
        // 先取消旧的提醒
        cancelReminder(memo.id)
        // 再设置新的提醒
        setReminder(memo)
    }
} 